﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OrganizationName.Factory.LifeTimeContracts
{
    public abstract class KeyedStorageLifeTimeContract : ILifeTimeContract
    {
        protected readonly string _InstanceDataKey = Guid.NewGuid().ToString();
        protected readonly string _InstanceSetDataKey = Guid.NewGuid().ToString();

        protected abstract object GetData(string key);
        protected abstract void SetData(string key, object instance);
        public abstract object SyncRoot { get; }

        public virtual object Instance
        {
            get
            {
                return GetData(_InstanceDataKey);
            }
            set
            {
                object syncRoot = SyncRoot;
                if(syncRoot == null)
                {
                    syncRoot = this;
                }
                lock (syncRoot)
                {
                    SetData(_InstanceDataKey, value);
                    SetData(_InstanceSetDataKey, true);
                }
            }
        }

        public virtual bool IsValid
        {
            get
            {
                return GetData(_InstanceSetDataKey) != null;
            }
        }


    }
}
